<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="orderNum" placeholder="请输入内容" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter"></el-input>

<!--      <el-select v-model="listQuery.importance" placeholder="订单状态" clearable style="width: 120px" class="filter-item">-->
<!--        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item"/>-->
<!--      </el-select>-->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column prop="index" label="序号" align="center" width="80" fixed>
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单号" prop="uubOdNum" align="center">

      </el-table-column>
      <el-table-column label="下单用户" prop="userMsg" align="center">

      </el-table-column>
      <el-table-column label="商家名" prop="brandMsg" align="center">

      </el-table-column>
      <el-table-column label="实付价格" prop="uubOdActualprice" align="center">

      </el-table-column>
      <el-table-column label="物流" prop="uubExpressId" align="center">

        <template slot-scope="row">

          <el-button v-if="row.status!='deleted'" size="mini" type="primary" round @click="getExpress(row.row)">
            查看物流信息
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="商品" prop="goodId" align="center">
        <template slot-scope="row">

          <el-button v-if="row.status!='deleted'" size="mini" type="success" round @click="getGoodMsg(row.row)">
            查看商品信息
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="保险" align="center" class-name="small-padding fixed-width">
        <template slot-scope="row">

          <el-button v-if="row.status!='deleted'" size="mini" type="primary" round @click="getSafes(row.row)">
            查看保险
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="下单时间" prop="uubOdCheckouttime" align="center">

      </el-table-column>
      <el-table-column label="结账时间" prop="uubOdCheckouttime" align="center">

      </el-table-column>
      <!--      操作-->
      <el-table-column label="操作" align="center"  class-name="small-padding fixed-width">
        <template slot-scope="row">

          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>


    <!--    分页-->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total=total>
      </el-pagination>
    </div>


    <!--    查看保险-->
    <el-dialog
      title="保险详细"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <!--弹窗内容-->
      <el-descriptions border>
        <el-descriptions-item label="投保人">{{ this.safe.userMsg }}</el-descriptions-item>
        <el-descriptions-item label="受保人">{{ this.safe.userMsg }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ this.safe.createTime }}</el-descriptions-item>
        <el-descriptions-item label="保障时间">{{ this.safe.safeTime }}天</el-descriptions-item>
        <el-descriptions-item label="保障价值">￥{{ this.safe.safeValue }}</el-descriptions-item>
        <el-descriptions-item label="保障信息">{{ this.safe.safeText }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>


    <!--    查看物流-->
    <el-dialog
      title="物流详细"
      :visible.sync="dialogVisible3"
      width="50%"
    >
      <!--物流弹窗内容-->
      <el-descriptions border>
        <el-descriptions-item label="物流单号">{{ this.express.expressNumber }}</el-descriptions-item>
        <el-descriptions-item label="发货地址">{{ this.express.deliveryAdd }}</el-descriptions-item>
        <el-descriptions-item label="收货地址">{{ this.express.takeAdd }}</el-descriptions-item>
        <el-descriptions-item label="物流状态">{{ this.express.expressStatus }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ this.express.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ this.express.updateTime }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>


    <!--    查看商品-->
    <el-dialog
      title="商品信息"
      :visible.sync="dialogVisible2"
      width="30%"
    >
      <!--弹窗内容-->
      <el-descriptions :column="1" border>
        <el-descriptions-item label="商品名称">{{this.good.goodDescription}}</el-descriptions-item>
        <el-descriptions-item label="商品价格">￥{{this.good.goodPrice}}</el-descriptions-item>
        <el-descriptions-item label="商品图片">      <!--        图片-->
          <el-image style="width: 150px; height: 150px; border:none;cursor: pointer;"
                    :src="getImage(this.good.goodImage)"
          >
          </el-image>
        </el-descriptions-item>
        <el-descriptions-item label="描述信息">{{this.good.goodDescription}}</el-descriptions-item>

      </el-descriptions>


    </el-dialog>


  </div>
</template>

<script>
import {fetchList, fetchPv, createArticle, updateArticle} from '@/api/article'
import waves from '@/directive/waves' // waves directive
import {parseTime} from '@/utils'
import Pagination from '@/components/Pagination'
import { deletuuborder, getUanduborder, getuubOrderTotal} from '@/api/order'
import {getExpress} from "@/api/express";
import {getGoods} from "@/api/goods";
import {getSafe} from "@/api/safe";

const calendarTypeOptions = [
  {key: 'CN', display_name: 'China'},
  {key: 'US', display_name: 'USA'},
  {key: 'JP', display_name: 'Japan'},
  {key: 'EU', display_name: 'Eurozone'}
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: {Pagination},
  directives: {waves},
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      orderNum: '',
      listLoading: true,
      //保险弹出
      dialogVisible: false,
      //商品
      dialogVisible2: false,
      //物流
      dialogVisible3: false,
      //物流信息
      express: {},
      //商品信息
      good:{},
      //保险内容
      safe: {},
      //分页总数
      total: 0,
      //当前页
      currentPage: 1,
      //每页多少条
      pagesizes: 5,


      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      importanceOptions: ["待付款", "待派送", "已派送", "已完成", "已取消"],
      calendarTypeOptions,
      sortOptions: [{label: 'ID Ascending', key: '+id'}, {label: 'ID Descending', key: '-id'}],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{required: true, message: 'type is required', trigger: 'change'}],
        timestamp: [{type: 'date', required: true, message: 'timestamp is required', trigger: 'change'}],
        title: [{required: true, message: 'title is required', trigger: 'blur'}]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      getuubOrderTotal().then(res=>{
        // console.log(res)
        this.total=res.data
      })


      getUanduborder(this.orderNum,this.currentPage, this.pagesizes).then(res => {
        this.list = res.data

        console.log(this.list)
        this.listLoading = false

      })
    },
    handleFilter() {
      // this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const {prop, order} = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {

      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletuuborder(row.row.uubOdId).then(res => {
          console.log(res)
          this.$notify({
            title: res.data,
            message: res.data,
            type: 'success',
            duration: res.code
          })
        })
        this.getList();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //查看物流
    getExpress(row) {
      console.log(row)
      getExpress(row.uubExpressId).then(res => {
        console.log(res.data)
        if (res.data == null) {
          this.$notify({
            title: "出错了-_-!!!!",
            message: "暂无物流信息",
            type: 'error',
          })
        }
        this.express = res.data
        if (this.express.expressStatus==1){
          this.express.expressStatus='待付款'
        }
        if (this.express.expressStatus==2){
          this.express.expressStatus='待派送'
        }
        if (this.express.expressStatus==3){
          this.express.expressStatus='已派送'
        }
        if (this.express.expressStatus==4){
          this.express.expressStatus='已完成'
        }
        if (this.express.expressStatus==5){
          this.express.expressStatus='已取消'
        }
        console.log(this.express)
        this.dialogVisible3 = true
      })
    },
    //查看商品
    getGoodMsg(row) {
      console.log(row)
      getGoods(row.goodId).then(res=>{
        if (res.data == null) {
          this.$notify({
            title: "出错了-_-!!!!",
            message: "暂无商品信息",
            type: 'error',
          })
        }
        this.good=res.data
        this.dialogVisible2 = true

      })

    },
    //查看保险
    getSafes(row) {
      this.safe.userMsg = row.userMsg
      this.safe.createTime = row.createTime
      getSafe(row.safeId).then(res => {
        if (res.data == null) {
          this.$notify({
            title: "出错了-_-!!!!",
            message: "暂无保险",
            type: 'error',
          })
        }
        this.safe.safeText = res.data.safeText
        this.safe.safeTime = res.data.safeTime
        this.safe.safeValue = res.data.safeValue
        this.dialogVisible = true
      })

    },
    //得到图片
    getImage(image) {
      // console.log("imageimageimag")
      // console.log(image)
      return `http://localhost:9527/dev-api/common/download?name=${image}`
    },
    // 分页
    handleSizeChange(val) {
      this.pagesizes = val
      console.log(this.pagesizes)
      this.getList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      console.log(this.currentPage);
      this.getList()
    },













    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },


  }
}
</script>
